﻿using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Linq;

namespace Ekton_Manage_InfrastructureCore.Common
{
    public class Appsettings
    {
        /// <summary>
        /// 配置文件的根节点
        /// </summary>
        private static readonly IConfigurationRoot _config;
        public static Dictionary<string, string> DbDicData = new Dictionary<string, string>();
        /// <summary>
        /// Constructor
        /// </summary>
        static Appsettings()
        {
            // 加载appsettings.json，并构建IConfigurationRoot
            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                                                    .AddJsonFile("appsettings.json", true, true);
            _config = builder.Build();
        }
        private static readonly object SingLock = new object();
        public static async Task GetDicData()
        {
            DbDicData.Clear();
            if (bool.Parse(_config["Db:MySql:ConnectionData:Enabled"]))
                DbDicData.Add("MySql", _config["Db:MySql:ConnectionData:Priority"] + "&" + _config["Db:MySql:ConnectionData:dbconn"]);
            if (bool.Parse(_config["Db:SqlServer:ConnectionData:Enabled"]))
                DbDicData.Add("SqlServer", _config["Db:SqlServer:ConnectionData:Priority"] + "&" + _config["Db:SqlServer:ConnectionData:dbconn"]);
            if (bool.Parse(_config["Db:PostgreSql:ConnectionData:Enabled"]))
                DbDicData.Add("PostgreSql", _config["Db:PostgreSql:ConnectionData:Priority"] + "&" + _config["Db:PostgreSql:ConnectionData:dbconn"]);
            if (bool.Parse(_config["Db:Sqlite:ConnectionData:Enabled"]))
                DbDicData.Add("Sqlite", _config["Db:Sqlite:ConnectionData:Priority"] + "&" + _config["Db:Sqlite:ConnectionData:dbconn"]);
        }

        public static async Task<Tuple<string, string>> GetConnectionObject()
        {
            lock (SingLock)
            {
                GetDicData();
                var result = ((from temp in DbDicData orderby Convert.ToInt32(temp.Value.Split('&')[0].Trim()) ascending select temp).
                              ToDictionary(pair => pair.Key, pair => pair.Value.Split('&')[1].Trim()));
                return Tuple.Create<string, string>(result.FirstOrDefault().Key, result.FirstOrDefault().Value);
            }
        }

        /// <summary>
        /// EnableDb
        /// </summary>
        public static string EnableDb => _config["ConnectionStrings:Enable"];

        /// <summary>
        /// ConnectionStrings
        /// </summary>
        public static string ConnectionStrings => _config.GetConnectionString(EnableDb);
    }
}
